package com.example.service;

import com.example.base.exception.CustomException;
import com.example.entity.Customer;
import com.example.entity.Params;

import com.example.mapper.CalenderMapper;
import com.example.mapper.CustomerMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CustomerService {
    @Autowired
    private CustomerMapper customerMapper;

    public PageInfo<Customer> findBySearch(Params params) {
        //开启分页查询
        PageHelper.startPage(params.getPageNum(), params.getPageSize());

        List<Customer> list = customerMapper.findBySearch(params);
        return PageInfo.of(list);
    }


    public void add(Customer user) {
        //1.用户名一定要有，否则不允许添加(需要用户名登录)
        if (user.getName() == null || "".equals(user.getName())) {
            throw new CustomException("用户名不能为空");
        }
        //2.进行重复性判断，同一名字的管理员不允许重复添加
        Customer admin = customerMapper.findByName(user.getName());
        if (admin != null) {
            throw new CustomException("该用户名已存在");
        }
        //初始化一个密码
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        customerMapper.add(user);
    }

    public Customer login(Customer user) {
        if (user.getName() == null || "".equals(user.getName())) {
            throw new CustomException("用户名不能为空");
        }
        if (user.getPassword() == null || "".equals(user.getPassword())) {
            throw new CustomException("密码不能为空");
        }
        Customer admin = customerMapper.findByNameAndPassword(user.getName(), user.getPassword());
        if (admin == null) {
            throw new CustomException("用户名或密码错误");
        }
        return admin;
    }

    public void update(Customer user) {
        customerMapper.update(user);
    }

    public void delete(Integer id) {

        customerMapper.deleteById(id);
    }
}
